package com.huli.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huli.mapper.SysRoleMapper;
import com.huli.mapper.SysUserMapper;
import com.huli.mapper.UserMapper;
import com.huli.pojo.SysRole;
import com.huli.pojo.SysUser;
import com.huli.service.SysUserService;
import com.huli.vo.OrganizationUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {
    // 注入SysUserMapper
    @Autowired
    private SysUserMapper sysUserMapper;
    // 注入SysRoleMapper
    @Autowired
    private SysRoleMapper sysRoleMapper;
    // 实现SysUserService接口中的userList方法
    @Override
    public OrganizationUserVo userList(OrganizationUserVo param) {
        // 使用PageHelper插件进行分页
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        // 调用sysUserMapper中的userList方法获取用户列表
        List<SysUser> sysUserList = sysUserMapper.userList();
        // 遍历用户列表
        for (SysUser sysUser : sysUserList) {
            // 调用sysRoleMapper中的roleList方法获取用户角色
            SysRole sysRole = sysRoleMapper.roleList(sysUser.getUserType());
            // 设置用户角色名称
            sysUser.setRoleName(sysRole.getRoleName());
        }
        // 将用户列表封装到PageInfo中
        PageInfo<SysUser> sysUserPageInfo = new PageInfo<>(sysUserList);
        // 返回封装后的用户列表
        return new OrganizationUserVo(sysUserPageInfo.getTotal(),sysUserList);
    }

    @Override
    // 重写父类方法，删除指定id的用户
    public void deleteUser(Long id) {
        // 调用sysUserMapper的deleteById方法，根据id删除用户
        sysUserMapper.deleteById(id);
    }

    @Override
    // 重写父类方法，更新用户信息
    public void updateUser(SysUser sysUser) {
        // 设置更新时间
        sysUser.setUpdateTime(new Date());
        // 调用Mapper接口更新用户信息
        sysUserMapper.updateUser(sysUser);
    }

    @Override
    // 重写父类方法，添加用户
    public void addUser(SysUser sysUser) {
        // 设置用户创建时间
        sysUser.setCreateTime(new Date());
        // 调用Mapper接口，插入用户
        sysUserMapper.insertUser(sysUser);
    }

    @Override
    // 根据id更新用户信息
    public SysUser updateUserById(Long id) {
        // 调用sysUserMapper的getUserById方法，根据id获取用户信息
        return sysUserMapper.getUserById(id);
    }
}
